/*
 * @Autor: dingxiaolin
 * @Date: 2020-05-05 09:05:31
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-05-11 21:55:46
 */
'use strict';

const BUCKET = 'fc-ws';
const WORK_DIR = 'fc-chat/';

var co = require('co');
var OSS = require('ali-oss');

module.exports.register = function (event, context, callback) {
  console.log('event: %s', event);
  var evt = JSON.parse(event);
  var deviceId = evt['headers']['x-ca-deviceid'];
  var requestDomain = evt['headers']['requestDomain'];
  var requestId = evt['headers']['requestId'];
  var clientIP = evt['headers']['clientIP'];
  var ossClient = getOSSClient(context);

  var resp = {
    'isBase64Encoded': 'false',
    'statusCode': '200',
    'body': {
      'deviceId': deviceId,
      'requestDomain': requestDomain,
      'requestId': requestId,
      'clientIP': clientIP
    },
  };

  var response = async () => {
    try {
      var onlineUsers = await getOnlineUsers(ossClient);
      console.log('online users: %j', onlineUsers);
      onlineUsers[deviceId] = 'online';
      await setOnlineUsers(ossClient, onlineUsers);
      console.log('set online users: %j', onlineUsers);
      callback(null, resp);
    } catch (err) {
      console.error(err);
      callback(err);
    }
  }
  response();
};


var getOnlineUsers = async (ossClient) => {
  var usersKey = WORK_DIR + 'online.json';
  var users = {};
  try {
    var resp = await ossClient.get(usersKey);
    return JSON.parse(resp.content.toString());
  } catch (err) {
    return users;
  }
};

var setOnlineUsers = async (ossClient, users) => {
  var usersKey = WORK_DIR + 'online.json';
  await ossClient.put(usersKey, new Buffer(JSON.stringify(users)));
};

var getOSSClient = (context) => {
  return new OSS({
    accessKeyId: context.credentials.accessKeyId,
    accessKeySecret: context.credentials.accessKeySecret,
    stsToken: context.credentials.securityToken,
    region: 'oss-' + context.region,
    internal: true,
    secure: true,
    bucket: BUCKET,
  });
};
